package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.BaseContext;
import com.itheima.DTO.LoginDTO;
import com.itheima.DTO.UserYddArticlePageDTO;
import com.itheima.DTO.YddCateDTO;
import com.itheima.VO.*;
import com.itheima.constant.LoginConstant;
import com.itheima.entity.*;
import com.itheima.mapper.*;
import com.itheima.service.IndexService;
import com.itheima.service.SysConfigService;
import com.itheima.util.IpUtils;
import com.itheima.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.itheima.exception.AccountException;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class IndexServiceImpl implements IndexService {

    private final JwtUtil jwtUtil;
    private final IpUtils ipUtils;
    private final SysUserMapper sysUserMapper;
    private final SysRoleMapper sysRoleMapper;
    private final SysMenuMapper sysMenuMapper;
    private final SysDictMapper sysDictMapper;
    private final ConfigMapper configMapper;
    private final YddCateMapper yddCateMapper;
    private final YddTagMapper yddTagMapper;
    private final YddArticleMapper yddArticleMapper;
    private final SysConfigService sysConfigService;
    private final YddLinkMapper yddLinkMapper;
    private final YddAdvimgMapper yddAdvimgMapper;
    private final YddAdvposMapper yddAdvposMapper;
    private final YddUserMapper yddUserMapper;


    @Override
    public UserLoginVO login(LoginDTO loginDTO) {
        SysUser sysUser = sysUserMapper.selectSysUserByName(loginDTO.getLogin_name());
        if(Objects.isNull(sysUser)){
            throw new AccountException("账号不存在");
        }
        String digest = DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes());
        if(!Objects.equals(digest,sysUser.getPassword())){
            throw new AccountException("密码错误！");
        }

        sysUser.setLoginIp(ipUtils.getClientIp());
        sysUser.setLoginDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());

        sysUserMapper.updateSysUserById(sysUser);
        BaseContext.setLoginUserId(sysUser.getId());

        HashMap<String,Object> hashMap = new HashMap<>(8);
        hashMap.put(LoginConstant.USER_ID, sysUser.getId());
        String jwt = jwtUtil.createJWT(hashMap);
        return UserLoginVO.builder().token(jwt).build();
    }

    @Override
    public ProfileVO profile() {
        ProfileVO profileVO = new ProfileVO();
        YddUserVO yddUserVO = getUserInfoVO();
        List<MenuVO> menuVOList = getMenuVOList(yddUserVO);
        Map<String,HashMap<String,String>> dictsList = getMap();
        List<String> btnList = getStringList();

        profileVO.setUserInfo(yddUserVO);
        profileVO.setMenuList(menuVOList);
        profileVO.setDictsList(dictsList);
        profileVO.setBtnList(btnList);

        return profileVO;
    }

    @Override
    public HashMap<?, ?> getConfig() {
        String tabValue = "system";
        List<SysConfig> configList = configMapper.selectByName(tabValue);
        HashMap<String, String> hashMap = new HashMap();
        //遍历集合
        configList.forEach(config -> {
            hashMap.put(config.getAttrKey(), config.getAttrValue());
        });
        return hashMap;
    }

    @Override
    public YddArticleShowVO selectArticeleInfoById(Integer id) {
        YddArticle info = yddArticleMapper.selectById(id);
        ArticleVO yddArticleVO = new ArticleVO();
        BeanUtils.copyProperties(info, yddArticleVO);
        yddArticleVO.setUpdate_date(info.getUpdateDate());
        yddArticleVO.setCreate_date(info.getCreateDate());
        List<YddArticle> recommend = yddArticleMapper.selectRecommendYddArticle();

        SimpleArticleVO prev = new SimpleArticleVO();
        prev.setId(id - 1);
        YddArticle yddArticlePrev = yddArticleMapper.selectById(id - 1);
        prev.setTitle(yddArticlePrev.getTitle());

        SimpleArticleVO next = new SimpleArticleVO();
        next.setId(id - 1);
        YddArticle yddArticleNext = yddArticleMapper.selectById(id - 1);
        next.setTitle(yddArticleNext.getTitle());

        YddArticleShowVO yddArticleShowVO = new YddArticleShowVO();
        yddArticleShowVO.setPrev(prev);
        yddArticleShowVO.setNext(next);
        yddArticleShowVO.setInfo(yddArticleVO);
        yddArticleShowVO.setRecommend(recommend);

        return yddArticleShowVO;
    }

    @Override
    public IndexVO selectAll() {

        List<YddCate> yddCateList = yddCateMapper.selectAllCate();
        List<CateVO> cateVOList = yddCateList.stream().map(yddCate -> {
            CateVO cateVO = new CateVO();
            BeanUtils.copyProperties(yddCate,cateVO);
            return cateVO;
        }).collect(Collectors.toList());

        List<AdvimgVO> advimgVOList = yddAdvimgMapper.selectAllAdvimg();

        List<AdvimgVO> advimgVOList1 = advimgVOList.stream().filter(advimgVO -> {
            return advimgVO.getAdvimgpos().equals("13")||advimgVO.getAdvimgpos().equals("12");
        }).collect(Collectors.toList());

        List<AdvimgVO> advimgVOList2 = advimgVOList.stream().filter(advimgVO -> {
            return advimgVO.getAdvimgpos().equals("15");
        }).collect(Collectors.toList());

        List<AdvimgVO> advimgVOList3 = advimgVOList.stream().filter(advimgVO -> {
            return advimgVO.getAdvimgpos().equals("14");
        }).collect(Collectors.toList());

        IndexVO indexVO = new IndexVO();
        indexVO.setAllCate(cateVOList);
        indexVO.setConfig(sysConfigService.selectAllConfigData());
        indexVO.setAllTag(yddTagMapper.tagAllData());
        indexVO.setAllLink(yddLinkMapper.linkAllData());
        indexVO.setBanner(advimgVOList2);
        indexVO.setSideBanner(advimgVOList3);
        indexVO.setShowBanner(advimgVOList1);

        return indexVO;
        
    }

    @Override
    public HotArticleVO selectHotArticle(Integer page, Integer limit) {
        long now = System.currentTimeMillis();
        Integer num_day = yddArticleMapper.selectCountByTime(now - 24*60*60*1000);
        Integer num_week = yddArticleMapper.selectCountByTime(now - 7*24*60*60*1000);
        PageHelper.startPage(page, limit);
        List<YddArticle> yddArticleList = yddArticleMapper.selectAll();
        List<ArticleVO> articleVOList = yddArticleList.stream().map(yddArticle -> {
            ArticleVO articleVO = new ArticleVO();
            BeanUtils.copyProperties(yddArticle,articleVO);
            articleVO.setUpdate_date(yddArticle.getUpdateDate());
            articleVO.setCreate_date(yddArticle.getCreateDate());
            return articleVO;
        }).collect(Collectors.toList());
        PageInfo<ArticleVO> pageInfo = new PageInfo<>(articleVOList);
        PageVO pageVO = new PageVO();
        pageVO.setCount(yddArticleList.size());
        pageVO.setTotalPages(pageInfo.getPages());
        pageVO.setPageSize(limit);
        pageVO.setCurrentPage(page);
        pageVO.setData(pageInfo.getList());

        HotArticleVO hotArticleVO = new HotArticleVO();
        hotArticleVO.setNum_day(num_day);
        hotArticleVO.setNum_week(num_week);
        hotArticleVO.setList(pageVO);

        return hotArticleVO;
    }

    @Override
    public NewArticleVO selectNewArticle() {
        NewArticleVO newArticleVO = new NewArticleVO();
        List<ArticleVO> articleVOList = yddArticleMapper.selectNewArticle();
        newArticleVO.setList(articleVOList);
        return newArticleVO;
    }

    @Override
    public RecommendArticleVO selectRecommendArticle() {
        RecommendArticleVO recommendArticleVO = new RecommendArticleVO();
        List<ArticleVO> articleVOList = yddArticleMapper.selectRecommendArticle();
        recommendArticleVO.setList(articleVOList);
        return recommendArticleVO;
    }

    @Override
    public InsertPageVO page(UserYddArticlePageDTO userYddArticlePageDTO) {
        PageHelper.startPage(userYddArticlePageDTO.getPage(),userYddArticlePageDTO.getLimit());
        List<YddArticle> yddArticleList = yddArticleMapper.selectArticleByCateId(userYddArticlePageDTO.getCateid());
        List<ArticleVO> articleVOList = getYddArticleVOList(yddArticleList);
        PageInfo<ArticleVO> pageInfo = new PageInfo<>(articleVOList);
        PageVO pageVO = new PageVO();
        pageVO.setCount(yddArticleList.size());
        pageVO.setTotalPages(pageInfo.getPages());
        pageVO.setPageSize(userYddArticlePageDTO.getLimit());
        pageVO.setCurrentPage(userYddArticlePageDTO.getPage());
        pageVO.setData(pageInfo.getList());
        InsertPageVO insertPageVO = new InsertPageVO();
        insertPageVO.setList(pageVO);

        return insertPageVO;
    }

    @Override
    public BaseInfoVO baseInfo() {
        List<YddCateDTO> yddCateList = yddCateMapper.selectList();
        yddCateList.forEach(yddCate -> {
            Integer count = yddArticleMapper.selectCountByCateId(yddCate.getId());
            yddCate.setNum(count);
        });
        BaseInfoVO baseInfoVO = new BaseInfoVO();
        Integer advposCount = yddAdvposMapper.selectCount();
        Integer tagCount = yddTagMapper.selectCount();
        Integer adminCount = sysUserMapper.selectCount();
        Integer articleCount = yddArticleMapper.selectCount();
        Integer cateCount = yddCateMapper.selectCount();
        Integer advimgCount = yddAdvimgMapper.selectCount();
        List<YddUser> yddUserList = yddUserMapper.selectNewUserList();
        List<YddArticle> yddArticleList = yddArticleMapper.selectHotArticleList();
        Integer total = yddUserMapper.selectCount();
        Integer man = yddUserMapper.selectCountBySex(0);
        Integer woman = yddUserMapper.selectCountBySex(1);

        UserNumVO userNumVO = new UserNumVO();
        userNumVO.setTotal(total);
        userNumVO.setUser_man(man);
        userNumVO.setUser_woman(woman);

        baseInfoVO.setAll_cate(yddCateList);
        baseInfoVO.setAdvpos_num(advposCount);
        baseInfoVO.setTag_num(tagCount);
        baseInfoVO.setAdmin_num(adminCount);
        baseInfoVO.setArticle_num(articleCount);
        baseInfoVO.setCate_num(cateCount);
        baseInfoVO.setAdvimg_num(advimgCount);
        baseInfoVO.setNew_user(yddUserList);
        baseInfoVO.setHot_article(yddArticleList);
        baseInfoVO.setUser(userNumVO);

        return baseInfoVO;
    }

    private YddUserVO getUserInfoVO() {
        String loginUserId = BaseContext.getLoginUserId();
        SysUser sysUser = sysUserMapper.selectUserInfoByRoleId(loginUserId);
        String roleId = sysUser.getRoleId();
        YddUserVO yddUserVO = new YddUserVO();

        if(roleId != null && !roleId.isEmpty()){//判空
            JSONArray roleIds = JSON.parseArray(roleId); // 将角色ID字符串解析为 JSONArray 对象
            List<String> roleIdsList = roleIds.toJavaList(String.class);// 将 JSONArray 转换为 List<String>
            yddUserVO.setRole_id(roleIdsList);
            List<String> roleNameList = sysRoleMapper.selectNameListByIds(roleIdsList);
            yddUserVO.setRolename(roleNameList);
        }

        yddUserVO.setId(sysUser.getId());
        yddUserVO.setLogin_name(sysUser.getLoginName());
        yddUserVO.setName(sysUser.getName());
        yddUserVO.setEmail(sysUser.getEmail());
        yddUserVO.setPhone(sysUser.getPhone());
        yddUserVO.setLogin_ip(sysUser.getLoginIp());
        yddUserVO.setLogin_date(sysUser.getLoginDate());
        yddUserVO.setCreate_date(sysUser.getCreateDate());
        yddUserVO.setUpdate_date(sysUser.getUpdateDate());
        yddUserVO.setDel_flag(sysUser.getDelFlag());
        yddUserVO.setStatus(sysUser.getStatus());
        yddUserVO.setDefault_data(sysUser.getDefaultData());

        return yddUserVO;
    }

    private List<MenuVO> getMenuVOList(YddUserVO yddUserVO) {
        List<SysMenu> sysMenuList = sysMenuMapper.selectMenuInfoByRoleId(yddUserVO.getRole_id());
        return sysMenuList.stream().map(sysMenu -> {
            MenuVO menuVO = new MenuVO();
            menuVO.setId(sysMenu.getId());
            menuVO.setPid(sysMenu.getPid());
            menuVO.setPath(sysMenu.getPath());
            menuVO.setComponent(sysMenu.getComponent());
            menuVO.setTitle(sysMenu.getTitle());
            menuVO.setIcon(sysMenu.getIcon());
            menuVO.setIs_show(sysMenu.getIsShow());
            menuVO.setIs_cache(sysMenu.getIsCache());
            menuVO.setIs_link(sysMenu.getIsLink());
            menuVO.setRedirect(sysMenu.getRedirect());
            menuVO.setCreate_date(sysMenu.getCreateDate());
            menuVO.setUpdate_date(sysMenu.getUpdateDate());
            menuVO.setDel_flag(sysMenu.getDelFlag());
            menuVO.setType(sysMenu.getType());
            menuVO.setSort(sysMenu.getSort());
            menuVO.setMark(sysMenu.getMark());
            return menuVO;
        }).collect(Collectors.toList());
    }

    private Map<String, HashMap<String,String>> getMap() {
        HashMap<String, HashMap<String,String>> dictList = new HashMap<>();
        List<SysDict> sysDictList = sysDictMapper.selectDictList();
        sysDictList.forEach(sysDict -> {
            if (!dictList.containsKey(sysDict.getType())){
                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put(sysDict.getValue(),sysDict.getLabel());
                dictList.put(sysDict.getType(),hashMap);
            }
            else {
                HashMap<String,String> hashMap = dictList.get(sysDict.getType());
                hashMap.put(sysDict.getValue(),sysDict.getLabel());
                dictList.put(sysDict.getType(),hashMap);
            }
        });
        return dictList;
    }

    private List<String> getStringList() {
        ArrayList<String> btnList = new ArrayList<>();
        btnList.add("*");
        return btnList;
    }


    private List<ArticleVO> getYddArticleVOList(List<YddArticle> yddArticleList) {
        List<ArticleVO> articleVOList = yddArticleList.stream().map(yddArticle -> {
            ArticleVO articleVO = new ArticleVO();
            BeanUtils.copyProperties(yddArticle, articleVO);
            articleVO.setCreate_date(yddArticle.getCreateDate());
            articleVO.setUpdate_date(yddArticle.getUpdateDate());
            return articleVO;
        }).collect(Collectors.toList());
        return articleVOList;
    }

}


